package com.server.task;

import com.eureka.bean.AbsInstance;
import com.server.bean.Instance;
import com.server.database.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2023/1/28 11:20
 */
@Slf4j
public class MyTask extends TimerTask {

    private static final String SEND_HEART_BEAT = "/sendHeartBeat";

    private Instance instance;

    @Autowired
    private RestTemplate restTemplate;

    public MyTask(Instance instance) {
        this.instance = instance;
    }

    @Override
    public void run() {
        log.info("---------------------------start task---------------------------");

        log.info("start check instance heart beat");
        sendInstanceHeartBeat();
        log.info("end check instance heart beat");

        log.info("start print instance list");
        DataSource.printInstanceByGroup();
        log.info("end print instance list");

        log.info("---------------------------end task---------------------------");
    }


    /**
     * 主动检测实例是否存活
     */
    private void sendInstanceHeartBeat() {
        try {
            /**
             * 从注册中心获取实例信息
             */
            ConcurrentHashMap<String, AbsInstance> instanceConcurrentHashMap = DataSource.getInstanceConcurrentHashMap();
            instanceConcurrentHashMap.values().stream()
                    .filter(obj -> {
                        if (String.format("%s%s", obj.getIp(), obj.getPort()).equals(getCurKey())) {
                            // 是当前服务自己，跳过
                            return false;
                        }
                        return true;
                    }).forEach(object -> {
                /**
                 * 获取实例信息
                 * 拼接url
                 * 发送心跳
                 * 验证方法：只有不报错，说明调通，服务就正常
                 */
                String url = String.format("%s%s%s%s%s", "http://", object.getIp() + ":", object.getPort(), object.getContextPath(), SEND_HEART_BEAT);
                try {
                    restTemplate.getForObject(url, Boolean.class);
                } catch (Exception e) {
                    log.error("url:{} .err reason: {}", url, e);
                    DataSource.remove(object);// 从实例列表移除
                }
            });
            // Instance instance = restTemplate.getForObject(INSTANCE, Instance.class);
            // 存储数据
            DataSource.add(instance);
        } catch (Exception e) {
            log.error("{}", e);
        }

    }

    private String getCurKey() {
        return String.format("%s%s", instance.getIp(), instance.getPort());
    }
}
